package server;

import server.core.Context;
import server.core.Host;

import java.io.InputStream;
import java.net.Socket;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private List<Host> hostList;

    public RequestProcessor(Socket socket, List<Host> hostList) {
        this.socket = socket;
        this.hostList = hostList;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            outend:
            for (Host host : hostList) {
                if (host.getName().equals(request.getHost())) {
                    for (Context context : host.getAppList()) {
                        if (request.getUrl().startsWith(context.getBaseContextPath())) {
                            String resPath = request.getUrl().replace(context.getBaseContextPath(), "");
                            // 静态资源处理
                            if(context.getServletMap().get(resPath) == null) {
                                response.outputHtml(resPath);
                                break outend;
                            }else{
                                // 动态资源servlet请求
                                HttpServlet httpServlet = context.getServletMap().get(resPath);
                                httpServlet.service(request,response);
                                break outend;
                            }
                        }
                    }
                }
            }
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
